package top.whysu.rongcloud.service.impl;

import io.rong.messages.ContactNtfMessage;
import io.rong.messages.TxtMessage;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import top.whysu.rongcloud.api.dto.messages.InformationNtfMessage;
import top.whysu.rongcloud.constant.CodeConstant;
import top.whysu.rongcloud.constant.RongCloudConstant;
import top.whysu.rongcloud.dao.RongCloudFriendshipDao;
import top.whysu.rongcloud.dao.RongCloudUserDao;
import top.whysu.rongcloud.dto.http.Response;
import top.whysu.rongcloud.dto.rongcloud.FriendInfoResultEntity;
import top.whysu.rongcloud.dto.rongcloud.FriendShipResultEntity;
import top.whysu.rongcloud.dto.rongcloud.friendship.*;
import top.whysu.rongcloud.exception.BusinessException;
import top.whysu.rongcloud.po.RongCloudFriendShipPO;
import top.whysu.rongcloud.po.RongCloudUserPO;
import top.whysu.rongcloud.service.RongCloudFriendShipService;
import top.whysu.rongcloud.util.CheckStringUtil;
import top.whysu.rongcloud.util.ResponseUtil;
import top.whysu.rongcloud.util.RongCloudUtil;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("RongCloudFriendShipServiceImpl")
public class RongCloudFriendShipServiceImpl implements RongCloudFriendShipService {

    @Resource
    RongCloudFriendshipDao rongCloudFriendshipDao;
    @Resource
    RongCloudUserDao rongCloudUserDao;

    @Override
    public Response wholeInvite(FriendShipInviteDTO requestDTO) {
        // 当前用户账号
        String userAccount = requestDTO.getUserAccount();
        // 好友账号
        String friendAccount = requestDTO.getFriendAccount();
        // 添加好友的验证信息
        String message = StringUtils.isBlank(requestDTO.getMessage())
                ? "我是 " + userAccount : requestDTO.getMessage();
        // 推送标题
        String pushContent = requestDTO.getPushContent();
        // 推送内容
        String pushData = requestDTO.getPushData();
        // 获取当前账号的昵称
        RongCloudUserPO rongCloudUserPO = rongCloudUserDao.selectByAccount(userAccount);
        if (rongCloudUserPO == null || StringUtils.isBlank(rongCloudUserPO.getNickname())) {
            throw new BusinessException(CodeConstant.RongCloud.ACCOUNT_NOT_EXIST, "账号\"" + userAccount + "\"未注册！");
        }
        String nickName = rongCloudUserPO.getNickname();
        // 请求者
        RongCloudFriendShipPO requester = rongCloudFriendshipDao.selectByAccount(userAccount, friendAccount);
        // 被请求者
        RongCloudFriendShipPO friend = rongCloudFriendshipDao.selectByAccount(friendAccount, userAccount);
        int requesterStatus, friendStatus;
        String action = "Added";
        String resultMessage = "无需对方确认，已成功添加好友";
        // 通过融云发送好友请求
        String extra = "{sourceUserNickname:" + nickName + ",version:123456}";
        if (requester != null && friend != null) {
            if (requester.getStatus() == RongCloudConstant.AGREED && friend.getStatus() == RongCloudConstant.AGREED) {
                return msg(CodeConstant.RongCloud.ALREADY_FRIEND, "你们已经是好友了", null);
            }
            if (friend.getStatus() == RongCloudConstant.AGREED || friend.getStatus() == RongCloudConstant.REQUESTING) {
                requesterStatus = RongCloudConstant.REQUESTING;
                friendStatus = RongCloudConstant.REQUESTED;
                action = "Sent";
                resultMessage = "请求已发送";
            } else if ((requester.getStatus() == RongCloudConstant.DELETED && friend.getStatus() == RongCloudConstant.DELETED)
                    || (requester.getStatus() == RongCloudConstant.AGREED && friend.getStatus() == RongCloudConstant.DELETED)
                    || (requester.getStatus() == RongCloudConstant.REQUESTING && friend.getStatus() == RongCloudConstant.IGNORED)
                    || (requester.getStatus() == RongCloudConstant.REQUESTING && friend.getStatus() == RongCloudConstant.REQUESTED)) {
                requesterStatus = RongCloudConstant.REQUESTING;
                friendStatus = RongCloudConstant.REQUESTED;
                action = "Sent";
                resultMessage = "请求已发送";
            } else {
                // 什么都不做
                return msg(RongCloudConstant.Code.SUCCESS, "什么都不做.", "None");
            }
            //更新状态
            requester.setStatus(requesterStatus);
            friend.setStatus(friendStatus);
            requester.setMessage("");
            friend.setMessage(message);
            requester.setUpdateTime(new Date());
            friend.setUpdateTime(new Date());
            rongCloudFriendshipDao.update(requester);
            rongCloudFriendshipDao.update(friend);
            // 通过融云发送好友请求
            if (friend.getStatus() == RongCloudConstant.REQUESTED) {
                sendContactMessage(RongCloudConstant.CONTACT_OPERATION_REQUEST, userAccount, friendAccount, message, pushContent, pushData, extra);
            }
        } else {
            // 之前没有加过好友
            if (userAccount.equals(friendAccount)) {
                // 自己加自己无条件通过
                saveFriendShip(userAccount, friendAccount, message, RongCloudConstant.AGREED);
            } else {
                // 请求者的 status为 requesting
                saveFriendShip(userAccount, friendAccount, "", RongCloudConstant.REQUESTING);
                // 被请求者的 status 为 requested
                saveFriendShip(friendAccount, userAccount, message, RongCloudConstant.REQUESTED);
                // 通过融云发送好友请求
                sendContactMessage(RongCloudConstant.CONTACT_OPERATION_REQUEST, userAccount, friendAccount, message, pushContent, pushData, extra);
            }
        }
        return msg(CodeConstant.Http.SUCCESS, resultMessage, action);
    }

    @Override
    public Response wholeAgree(@RequestBody @Validated FriendShipAccountDTO requestDTO) {
        // 当前用户id （被请求者）
        String userAccount = requestDTO.getUserAccount();
        // 请求者
        String requestAccount = requestDTO.getFriendAccount();
        // 查询账号是否存在
        RongCloudUserPO userPO = rongCloudUserDao.selectByAccount(userAccount);
        if (userPO == null) {
            throw new BusinessException(CodeConstant.RongCloud.ACCOUNT_NOT_EXIST, "账号不存在！");
        }
        RongCloudUserPO friendUserPO = rongCloudUserDao.selectByAccount(requestAccount);
        if (friendUserPO == null) {
            throw new BusinessException(CodeConstant.RongCloud.ACCOUNT_NOT_EXIST, "好友账号不存在！");
        }
        // 更新双方的 status为AGREE
        RongCloudFriendShipPO fd = rongCloudFriendshipDao.selectByAccount(userAccount, requestAccount);
        RongCloudFriendShipPO fg = rongCloudFriendshipDao.selectByAccount(requestAccount, userAccount);
        if (fg != null && fg.getStatus() != RongCloudConstant.REQUESTING && fg.getStatus() != RongCloudConstant.AGREED && fg.getStatus() != RongCloudConstant.REQUESTED) {
            return ResponseUtil.getResponse(CodeConstant.RongCloud.UNKNOW_FRIEND, "无效的好友请求，或者未知好友", null);
        }
        // 将双方的状态都置为同意
        rongCloudFriendshipDao.updateStatus(userAccount, requestAccount, RongCloudConstant.AGREED, new Date(), "");
        rongCloudFriendshipDao.updateStatus(requestAccount, userAccount, RongCloudConstant.AGREED, new Date(), "");
        // 给请求者 发一条消息说，我同意你的请求了
        String extra = "{sourceUserNickname:" + userPO.getNickname() + ",version:123456}";
        sendContactMessage(RongCloudConstant.CONTACT_OPERATION_ACCEPT_RESPONSE, userAccount, requestAccount,
                "我是" + userAccount + "，我已经同意你的好友请求了", "", "", extra);
        // 小灰条通知
        RongCloudUtil.sendPrivateMsg(userAccount, requestAccount,
                new InformationNtfMessage("你已添加了" + friendUserPO.getNickname() + "，现在可以开始聊天了。", ""));
        // 文本消息
        RongCloudUtil.sendPrivateMsg(userAccount, requestAccount,
                new TxtMessage("我通过了你的朋友验证请求，现在我们可以开始聊天了", ""));
        RongCloudUtil.sendPrivateMsg(requestAccount, userAccount,
                new TxtMessage(fd.getMessage(), ""));
        // 移除黑名单
        RongCloudUtil.removeBlackList(userAccount, requestAccount);
        RongCloudUtil.removeBlackList(requestAccount, userAccount);
        return ResponseUtil.getSuccessResponse();
    }

    @Override
    public void wholeIgnore(FriendShipAccountDTO requestDTO) {
        //状态为 忽略
        int i = rongCloudFriendshipDao.updateStatusWithOutDisplayTime(requestDTO.getUserAccount(),
                requestDTO.getUserAccount(), RongCloudConstant.IGNORED, new Date());
        if (i == 0) {
            throw new BusinessException(CodeConstant.RongCloud.UNKNOW_FRIEND, "无效的好友请求，或者未知好友");
        }
    }

    @Override
    public void delete(FriendShipAccountDTO requestDTO) {
        RongCloudFriendShipPO fg = rongCloudFriendshipDao.selectByAccount(requestDTO.getUserAccount(), requestDTO.getFriendAccount());
        if (fg == null || fg.getStatus() != RongCloudConstant.AGREED) {
            throw new BusinessException(CodeConstant.RongCloud.REJECT_OPERATION, "你们不是好友关系,不能执行相关操作");
        }
        fg.setDisplayName("");
        fg.setMessage("");
        fg.setStatus(RongCloudConstant.DELETED);
        fg.setUpdateTime(new Date());
        rongCloudFriendshipDao.update(fg);

        //添加到黑名单
        RongCloudUtil.addBlackList(requestDTO.getUserAccount(), requestDTO.getFriendAccount());
        RongCloudUtil.addBlackList(requestDTO.getFriendAccount(), requestDTO.getUserAccount());

    }

    @Override
    public void wholeSetDisplayTime(DisplayNameAccountDTO requestDTO) {
        String userAccount = requestDTO.getUserAccount();
        String friendAccount = requestDTO.getFriendAccount();
        String displayName = requestDTO.getDisplayName();
        if (displayName.length() > 32) {
            throw new BusinessException(CodeConstant.Http.PARAM_ERROR, "备注名长度不能超过32字节");
        }
        if (CheckStringUtil.containsEmoji(displayName)) {
            throw new BusinessException(CodeConstant.Http.PARAM_ERROR, "备注名不能包含emoji表情");
        }

        RongCloudFriendShipPO po = rongCloudFriendshipDao.selectByAccount(userAccount, friendAccount);
        if (po == null) {
            throw new BusinessException(CodeConstant.RongCloud.ACCOUNT_NOT_EXIST, "账号不存在！");
        }
        /*if(fs == null || fs.getStatus() != AGREED){
            return RongCloudResultUtil.error(CodeCOnstant.RongCloud.REJECT_OPERATION,"你们不是好友关系,不能执行相关操作");
        }*/
        po.setDisplayName(displayName);
        int re = rongCloudFriendshipDao.update(po);
        if (re == 0) {
            throw new BusinessException(CodeConstant.Http.FAIL, "修改备注名失败！");
        }
    }

    @Override
    public List<FriendShipResultEntity> getAllFriendShipList(FriendShipAllDTO requestDTO, boolean isNewFriendList) {
        if (requestDTO == null || StringUtils.isBlank(requestDTO.getUserAccount())) {
            throw new BusinessException(CodeConstant.Http.PARAM_ERROR, "入参为空！");
        }
        String userAccount = requestDTO.getUserAccount();
        Boolean getYourself = requestDTO.getGetYourself();
        // 前端需要的对象
        List<FriendShipResultEntity> resultList = new ArrayList<>();
        // 查找当前账号，status为同意的好友列表
        Map<String, Object> params = new HashMap<>();
        params.put("userAccount", userAccount);
        // 如果是“新的朋友”列表，则status为：请求； 否则的话是查询好友列表，status为同意
        if (isNewFriendList) {
            params.put("status", RongCloudConstant.REQUESTING);
        } else {
            params.put("status", RongCloudConstant.AGREED);
        }
        List<RongCloudFriendShipPO> friendShipList = rongCloudFriendshipDao.selectList(params);
        if (CollectionUtils.isNotEmpty(friendShipList)) {
            friendShipList.forEach(it -> {
                // 好友Id和本人Id一样，再判断要不要获得自己
                if (userAccount.equals(it.getFriendAccount()) && !getYourself) {
                    return;
                }
                // 是否是查询“新的朋友”列表
                if (isNewFriendList) {
                    // 如果好友那边删除了，或者忽略，则不展示在“新的朋友”列表
                    RongCloudFriendShipPO friendShipPO = rongCloudFriendshipDao.selectByAccount(it.getFriendAccount(), userAccount);
                    if (friendShipPO == null) {
                        return;
                    }
                    if (friendShipPO.getStatus() != null) {
                        if (friendShipPO.getStatus() == RongCloudConstant.DELETED || friendShipPO.getStatus() == RongCloudConstant.IGNORED) {
                            return;
                        }
                    }
                }
                // 前端要的对象
                FriendShipResultEntity resultEntity = new FriendShipResultEntity();
                resultEntity.setDisplayName(it.getDisplayName());
                resultEntity.setMessage(it.getMessage());
                resultEntity.setStatus(it.getStatus());
                Date date = it.getUpdateTime() == null ? new Date() : it.getUpdateTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                resultEntity.setUpdatedAt(sdf.format(date));
                // 查询好友的融云Id
                RongCloudUserPO rongCloudUserPO = rongCloudUserDao.selectByAccount(it.getFriendAccount());
                if (rongCloudUserPO != null) {
                    FriendShipResultEntity.UserEntity user = new FriendShipResultEntity.UserEntity();
                    user.setId(rongCloudUserPO.getRongCloudUserId());
                    user.setNickname(rongCloudUserPO.getNickname());
                    user.setPortraitUri(rongCloudUserPO.getAvatar());
                    resultEntity.setUser(user);
                }
                resultList.add(resultEntity);
            });
        }
        return resultList;
    }

    @Override
    public FriendInfoResultEntity getFriendInfo(FriendShipAccountDTO friendShipAccountDTO) {
        String userAccount = friendShipAccountDTO.getUserAccount();
        String friendAccount = friendShipAccountDTO.getFriendAccount();
        RongCloudFriendShipPO po = rongCloudFriendshipDao.selectByAccount(userAccount, friendAccount);
        if (po == null) {
            throw new BusinessException(CodeConstant.RongCloud.REJECT_OPERATION, "你们不是好友关系,不能执行相关操作");
        }
        FriendInfoResultEntity resultEntity = new FriendInfoResultEntity();
        resultEntity.setDisplayName(po.getDisplayName());
        FriendInfoResultEntity.UserEntity user = new FriendInfoResultEntity.UserEntity();
        // 好友信息
        RongCloudUserPO rongCloudUserPO = rongCloudUserDao.selectByAccount(friendAccount);
        user.setId(rongCloudUserPO.getRongCloudUserId());
        user.setNickname(rongCloudUserPO.getNickname());
        user.setSex(rongCloudUserPO.getSex());
        user.setPhone(rongCloudUserPO.getRongCloudUserId());
        user.setPortraitUri(rongCloudUserPO.getAvatar());
        user.setRegion("86");
        resultEntity.setUser(user);
        return resultEntity;
    }

    /**
     * 新增
     *
     * @param userAccount   当前用户账号
     * @param friendAccount 好友账号
     * @param message       信息
     * @param status        状态 {@link RongCloudConstant#AGREED}等
     * @author @2021-03-15 19:37
     */
    private void saveFriendShip(String userAccount, String friendAccount, String message, int status) {
        RongCloudFriendShipPO friendShip = new RongCloudFriendShipPO();
        friendShip.setUserAccount(userAccount);
        friendShip.setFriendAccount(friendAccount);
        friendShip.setMessage(message);
        friendShip.setStatus(status);
        friendShip.setCreateTime(new Date());
        friendShip.setUpdateTime(new Date());
        rongCloudFriendshipDao.insert(friendShip);
    }

    /**
     * 联系人(好友)通知消息,详见https://www.rongcloud.cn/docs/message_architecture.html#contact_notification_message
     */
    private void sendContactMessage(String contact, String senderId, String targetId, String message, String pushContent, String pushData, String extra) {
        ContactNtfMessage contactNtfMessage = new ContactNtfMessage(contact, extra, senderId, targetId, message);
        RongCloudUtil.sendSystemMessage(senderId, new String[]{targetId}, contactNtfMessage, pushContent, pushData);
    }

    /**
     * 提示小灰条通知消息
     */
    private void sendInformation(String senderId, String[] targetIds, String message, String pushContent, String pushData, String extra) {
        InformationNtfMessage informationNtfMessage = new InformationNtfMessage(message, extra);
        RongCloudUtil.sendSystemMessage(senderId, targetIds, informationNtfMessage, pushContent, pushData);
    }

    /**
     * 响应前端，主要是为了Action
     */
    private Response msg(int code, String msg, String action) {
        FriendShipActionDTO dto = new FriendShipActionDTO();
        dto.setAction(action);
        return ResponseUtil.getResponse(code, msg, dto);
    }

}
